var async = require('async'),
  user = require('../../app/model/user');

//////////
exports.pass = function(req, res, next, connection){
  //获取uid
  //通过uid获取角色id
  //通过角色id获取每个角色拥有资源
  //判断访问资源是否在资源池里面,进而判断是否拥有该资源权限
  if(req.user == undefined){
    res.send('without auth or user info');
    return;
  }
  var uid = req.user.id;
  var logData = {
    url: req._parsedUrl.path,     //完整的URL
    user: req.user.userName,      //用户名
    time: req._startTime,         //时间
    operation: req.route.method,  //操作类型
    data: req.body,               //操作数据
    resource: req.route.path      //资源路径
  };
  console.log('logData',logData);
  // console.log('connection:',connection);
  // console.log("operation: "+logData.operation);
  // console.log("resource: "+logData.resource);
  user.findResource(connection,uid,function(data){
    if(data.length == 0){//如果没有返回数据，表示没有对应用户或者没有对用户赋予操作
      console.log('without role or role hasnot privilege!');
      res.send('noPrivilege');
      return;
    }
    var flag = false;
    for(var i = 0; i < data.length; i ++){
      if(data[i].operation == logData.operation && data[i].resUrl == logData.resource){//如果存在资源和操作与请求资源和操作对应，就将标志置为true
        flag = true;
      }
    }
    if(flag){//存在资源和操作与请求资源和操作对应，则通过
       console.log(12);
      next();
    } else {//不存在返回没有角色信息
       console.log(11);
        console.log('without privilege!');
        res.send('noPrivilege');
        return;  
    }
  });
};

exports.test = function(req,res,next){

  console.log("user-auth test");
  next();
};